﻿using System;
using System.Linq;
using DAL.Engine;
using DAL.Engine.Interface;
using MongoDB.Driver;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using DAL.Mongo.Interface;
using MongoDB.Driver.Linq;

namespace DAL.Mongo.Repository
{
    public abstract class MongoRepository<TEntity, TKey> : IRepository<TEntity, TKey>
        where TEntity : IEntity<TKey>
    {
        protected readonly MongoCollection<TEntity> _collection;

        public MongoRepository(IConfigurationManager configurationManager)
        {
            _collection = configurationManager.GetCollectionFrom<TEntity>();
        }

        public TEntity Get(TKey id)
        {
            return _collection.FindOneByIdAs<TEntity>(BsonValue.Create(id));
        }

        public IEnumerable<TEntity> GetAll()
        {
            return _collection.FindAllAs<TEntity>();
        }

        public void Save(IEnumerable<TEntity> entities)
        {
            _collection.InsertBatch(entities.Where(e => e!=null && e.IsNew));
        }

        public void Save(TEntity entity)
        {
            if (entity.IsNew)
            {
                _collection.Insert<TEntity>(entity);
            }
            else
            {
                _collection.Save<TEntity>(entity);
            }
        }

        public void Delete(TKey id)
        {
            _collection.Remove(Query.EQ("_id", BsonValue.Create(id)));
        }
    }
}
